package com.mini.framework.ws.client.command;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;

import com.mini.framework.ws.client.Response;
import com.mini.framework.ws.client.parser.Parser;

public class PostWebService extends Command {
	
	private Logger log = Logger.getLogger("PostWebService");
	
	private static final String ENCODING_KEY = "encoding";
	
	public PostWebService(Parser parser){
		super(parser);
	}

	@Override
	public Response execute(String url,String method,Map<String,Object> params) {
		log.setLevel(Level.SEVERE);
		DefaultHttpClient httpclient = new DefaultHttpClient();
		HttpPost httpost = new HttpPost(url);
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		Iterator<String> keys = params.keySet().iterator();
		while(keys.hasNext()){
			String param = keys.next();
			String value = (String)params.get(param);
			nvps.add(new BasicNameValuePair(param, value));
		}
		UrlEncodedFormEntity urlEntity = null;
		try {
			String encoding = (String)params.get(ENCODING_KEY);
			if(encoding != null){
				urlEntity = new UrlEncodedFormEntity(nvps, (String)params.get(encoding));
			}else{
				urlEntity = new UrlEncodedFormEntity(nvps, HTTP.UTF_8);
			}
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
			log.severe(e1.getMessage());
		}
		httpost.setEntity(urlEntity);
		ResponseHandler<String> responseHandler = new BasicResponseHandler();
		String responseBody = null;
		try {
			responseBody = httpclient.execute(httpost, responseHandler);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			log.severe(e.getMessage());
		} catch (IOException e) {
			e.printStackTrace();
			log.severe(e.getMessage());
		}
		Response response = parser.doParse(responseBody);
		return response;
	}

}
